package com.jin.gulimall.ware.listener;

import com.jin.common.to.OrderTo;
import com.jin.gulimall.ware.service.WareSkuService;
import com.jin.gulimall.ware.to.StockLockedTo;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 监听信死队列
 */
@RabbitListener(queues = "stock.release.stock.queue")
@Service //要注入到容器中
public class RabbitMqListener {

    @Autowired
    WareSkuService wareSkuService;

    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("解锁库存的消息收到了...");
        try{
            wareSkuService.unLockStocked(to);
            System.out.println("解锁要成功了");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            System.out.println("解锁出现异常，重新入队");
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }

    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo to,Message message, Channel channel) throws IOException {
        System.out.println("订单解锁了，要通知库存一下");
        try {
            wareSkuService.unLockStocked(to);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            System.out.println("订单解锁后通知库存服务有异常了");
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
